package orfeu.engine;

import java.util.Iterator;
import java.util.Vector;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import AI.Hell;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;

public class GLRenderer implements GLSurfaceView.Renderer {
	private Context context;
	
	// list of objects that need to be rendered each frame
	public Vector<Sprite> drawList = new Vector<Sprite>();;
	
	/** sets context **/
	public void setContext(Context context) {
		this.context = context;
	}

	/** what to do when surface is created **/
	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
		gl.glShadeModel(GL10.GL_SMOOTH);
		gl.glClearDepthf(1.0f);
		gl.glEnable(GL10.GL_DEPTH_TEST);
		gl.glDepthFunc(GL10.GL_LEQUAL);
		gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
		gl.glEnable(GL10.GL_BLEND);
	    gl.glBlendFunc(GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA);
		
		// load textures for objects in draw list
		synchronized(drawList){
			try{
				for(int i=0; i < drawList.size() ;i++)
				{
					drawList.get(i).loadTexture(gl, context);
				}
				drawList.wait();
			}catch(InterruptedException e){

			}
		}
	}
	
	/** what to do when surface is changed **/
	public void onSurfaceChanged(GL10 gl, int width, int height) {
		// change the size of the viewport and do projection
		gl.glViewport(0, 0, width, height);
		gl.glMatrixMode(GL10.GL_PROJECTION);
		gl.glLoadIdentity();
		GLU.gluPerspective(gl, 45.0f, (float) width / (float) height, 0.1f, 600.0f);
		
		gl.glMatrixMode(GL10.GL_MODELVIEW);
		gl.glLoadIdentity();
	}
	
	/** draw the frame **/
	public void onDrawFrame(GL10 gl) {
		// clear the screen and depth buffer
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
		// reset to identity matrix
		gl.glLoadIdentity();

		// move everything towards the far plane of the view frustum
		gl.glTranslatef(0, 0, -590);
		
		drawElements(gl);
	}
	
	/*Make a Synchronized function that iterates and draws all the elements */
	public synchronized void drawElements(GL10 gl)
	{
		Sprite aux;
		synchronized (drawList) {
			try{
				Iterator<Sprite> it = drawList.iterator();
				while(it.hasNext()) {
					aux = it.next();
					//	synchronized (aux = it.next()) {
					if(aux.remove()) it.remove();
					//		aux.notifyAll();
					//	}
				}

				for (int i = 0; i < drawList.size(); i++) {
					//	synchronized (drawList.get(i)) {
					drawList.get(i).draw(gl);
					//		drawList.get(i).notifyAll();
					//	}
				}

				drawList.wait(10);
			}catch(InterruptedException e){

			}

		}
	}
	
}
